<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>原生JS实现拖拽</title>
		<style type="text/css">
			body {
				background-color: darksalmon;
			}

			.draggable {
				background-image: url('http://source.unsplash.com/random/150x150');
				position: relative;
				height: 150px;
				width: 150px;
				top: 5px;
				left: 5px;
				cursor: pointer;
			}

			.droppable {
				display: inline-block;
				height: 160px;
				width: 160px;
				margin: 10px;
				border: 3px salmon solid;
				background-color: white;
			}

			.dragging {
				border: 4px yellow solid;
			}

			.drag-over {
				background-color: #f4f4f4;
				border-style: dashed;
			}

			.invisible {
				display: none;
			}
		</style>
	</head>
	<body>
		<div class="droppable">
			<div class="draggable" draggable="true"></div>
		</div>
		<div class="droppable"></div>
		<div class="droppable"></div>
		<div class="droppable"></div>
		<div class="droppable"></div>
		<script type="text/javascript">
			// 查询draggable和droppable
			const draggable = document.querySelector('.draggable');
			const droppables = document.querySelectorAll('.droppable');

			// 监听draggable的相关事件
			draggable.addEventListener('dragstart', dragStart);
			draggable.addEventListener('dragend', dragEnd);

			function dragStart() {
				this.className += ' dragging';
				setTimeout(() => {
					this.className = 'invisible';
				}, 0);
			}

			function dragEnd() {
				this.className = 'draggable';
			}

			// 监听droppable的相关事件
			for (const droppable of droppables) {
				droppable.addEventListener('dragover', dragOver);
				droppable.addEventListener('dragleave', dragLeave);
				droppable.addEventListener('dragenter', dragEnter);
				droppable.addEventListener('drop', dragDrop);
			}

			function dragOver(e) {
				e.preventDefault();
			}

			function dragEnter(e) {
				e.preventDefault();
				this.className += ' drag-over';
			}

			function dragLeave(e) {
				this.className = 'droppable';
			}

			function dragDrop(e) {
				this.className = 'droppable';
				this.append(draggable);
			}
		</script>
	</body>
</html>
